using System;
using System.Linq;
using CommandSystem;
using CustomCharacter.Ability;
using Exiled.API.Features;
using Utils.NonAllocLINQ;

namespace CustomCharacter.Commands.AbilityManagerCommands
{
    public class Grant : ICommand
    {
        public bool Execute(ArraySegment<string> arguments, ICommandSender sender, out string response)
        {
            if (!sender.CheckPermission(PlayerPermissions.ForceclassWithoutRestrictions))
            {
                response = "你没有权限使用这条命令！（需要权限：ForceclassWithoutRestrictions）";
                return false;
            }

            if (arguments.Count < 2)
            {
                response = "用法：abilitymanager(am) grant 玩家ID 技能ID";
                return false;
            }

            if (!int.TryParse(arguments.At(0), out var id))
            {
                response = "请输入一个有效的数字ID";
                return false;
            }

            if (!Player.TryGet(id, out var player))
            {
                response = "无法找到指定的玩家！";
                return false;
            }

            if (!AbilityManager.RegisteredAbilities.TryGetFirst(x => x.AbilityId == arguments.At(1), out var ability))
            {
                response = "未找到指定已注册的技能，请输入abilitymanager list查询已注册技能";
                return false;
            }

            if (AbilityManager.Abilities.TryGetValue(player, out var ab) &&
                Enumerable.Any(ab, x => x.Ability == ability))
            {
                response = "该玩家已拥有此技能";
                return false;
            }

            player.GrantAbility(ability);
            response = "已给予玩家指定技能！";
            return true;
        }

        public string Command { get; } = "grant";
        public string[] Aliases { get; } = Array.Empty<string>();
        public string Description { get; } = "给予玩家技能";
    }
}